//
//  MainSubLibraryViewModel.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/10/22.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "MainSubLibraryViewModel.h"

@implementation MainSubLibraryViewModel

- (void)initialize
{
    [super initialize];
    
    @weakify(self);
    
    _articlesListData = nil;
    
    DataManager* dm = [DataManager sharedDataManager];
    self.provinceListData = dm.locationPLData;
    
    // 通知
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:Notify_FirstPageReload object:nil] subscribeNext:^(id x)
     {
         @strongify(self);
         
         NSNotification* notification = x;
         
         self.provinceListData = notification.object;
     }];
    
    self.reqDataCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
        
        return [self _requestArticleCategorySignal];
    }];
    
    self.chooseCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
        
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            
            [subscriber sendNext:input];
            [subscriber sendCompleted];
            
            return nil;
        }];
    }];
}

- (RACSignal*)_requestArticleCategorySignal
{
    @weakify(self);
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self);
        
        NSDictionary* postData = interface_param_getcatelist(@"3", self.provinceListData.areaID, @1, @10);
        
        @weakify(self);
        return [[AFNetWorkUtils racPOSTWthURL:url_interface_getcatelist params:postData] subscribeNext:^(id x)
                {
                    @strongify(self)
                    
                    /// 转化数据
                    @weakify(self);
                    
                    ArticlesListData* articlesListData = [ArticlesListData modelWithJSON:x];
                    
                    self.articlesListData = articlesListData;
                    
                    [subscriber sendNext:nil];
                    [subscriber sendCompleted];
                }   error:^(NSError *error) {
                    //错误处理
                    
                    [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:error.userInfo[customErrorInfoKey]}]];
                    [subscriber sendCompleted];
                }
                ];
        
        return nil;
    }];
}

@end
